package com.manager.controller;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.manager.pojo.TbCommodity;
import com.manager.pojo.TbInlibrary;
import com.manager.pojo.TbOutlibrary;
import com.manager.service.InLibraryService;
import com.manager.service.OutLibrarService;
import com.manager.service.StorageService;
import com.manager.vo.IDUtils;
import com.manager.vo.TbUserEx;
/**
 * 
 * @Title:  OutLibraryControl.java     
 * @Description:    出库controller
 * @author:      
 * @date:   2019年2月17日 下午2:27:40   
 * @version V1.0
 */
@Controller
public class OutLibraryControl {

	@Autowired
	private StorageService storageService; 
	
	@Autowired
	private OutLibrarService outLibrarService;
	
	
	@RequestMapping("/outlibrary-list")	//获取库存分页list
	public String getOutlibraryList(Integer page,Integer rows,String s_type,String like,Integer flag,String start,String end,Model model) {
		
		TbUserEx tbUserEx = new TbUserEx();
		
		if(flag!=null && flag == 1 && !start.isEmpty() && !end.isEmpty()) {
			
			Date dstart = null;
			Date dend = null;
			
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			
			try {
				dstart = sdf.parse(start);
				dend = sdf.parse(end);
			} catch (ParseException e) {
				e.printStackTrace();
			}
			
			tbUserEx = outLibrarService.getOutLibraryListByDateTime(page, rows, dstart, dend);
			
			tbUserEx.setFlag(flag);
			tbUserEx.setStart(start);
			tbUserEx.setEnd(end);
			model.addAttribute("tbUserEx", tbUserEx);
			
			return "outlibrary-list";
		}
		
		if(s_type == null || like==null || s_type.isEmpty() || like.isEmpty()) {	//判断查询模式
			s_type = null;
			like=null;
			tbUserEx.setS_type(null);
			tbUserEx.setLike(null);
		}

		
		
		if( s_type!=null && s_type.equals("name")) {	//商品名称查询
			
			like = like.trim();
			//like参数存在中文 进行转码
			try {
				like = new String(like.getBytes("ISO8859-1"),"utf-8");
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}  
			//获取 商品名称分页
			tbUserEx = outLibrarService.getOutLibraryListByName(page, rows, like);
			tbUserEx.setS_type(s_type);
			tbUserEx.setLike(like);
			
		}else if(s_type!=null && s_type.equals("type")) {	//商品类型查询
			
			like = like.trim();
			//like参数存在中文 进行转码
			
			try {
				like = new String(like.getBytes("ISO8859-1"),"utf-8");
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}  
			
			//获取分页查询
			tbUserEx = outLibrarService.getOutLibraryListByType(page, rows, like);
			tbUserEx.setS_type(s_type);
			tbUserEx.setLike(like);
			
		}else if(s_type!=null && s_type.equals("SKU")) {	//根据SKU查询
			
			like = like.trim();
			//获取分页查询
			tbUserEx = outLibrarService.getOutLibraryListBySKU(page, rows, like);
			tbUserEx.setS_type(s_type);
			tbUserEx.setLike(like);
		}else {
			
			//查询全部
			tbUserEx = outLibrarService.getOutLibraryList(page, rows);
			tbUserEx.setS_type(null);
			tbUserEx.setLike(null);
		}
		
		//判断成功失败码
		if(tbUserEx.getCode()!=200) {
			return "outlibrary-list";
		}
		
		//添加到model容器 方便前端访问查看
		model.addAttribute("tbUserEx", tbUserEx);
		
		return "outlibrary-list";
	}

	//出库添加页面的访问  根据ID获取库存的对象信息
	@RequestMapping("/outlibrary-add")
	public String outlibraryAdd(Integer id,Model model) {
		
		TbCommodity tbCommodity = null;
		
		try {
			tbCommodity = storageService.getTbCommodityById(id);
			
		}catch(Exception e) {
			e.printStackTrace();
		}
		
		model.addAttribute("tbCommodity", tbCommodity);
				
		return "outlibrary-add";
	}

	//出库添加操作
	@RequestMapping("/outlibraryadd")
	@ResponseBody
	public TbUserEx outlibraryAdds(TbOutlibrary tbOutlibrary,HttpServletRequest request) {
		
		TbUserEx tbUserEx = new TbUserEx();
		
		//路径拼接
		String webinf_root = request.getRealPath("/WEB-INF");
		String web_img_path = tbOutlibrary.getImg();
		web_img_path = web_img_path.substring(1, web_img_path.length());
		String old_img = webinf_root.concat(web_img_path);
		String new_img  = old_img.replaceAll("temp", "upload");
		
		File oldFile=new File(old_img);
		File newFile = new File(new_img);
		
        //通过CommonsMultipartFile的方法直接写文件（注意这个时候）
        try {
        	//文件拷贝临时文件复制到 upload目录
        	FileUtils.copyFile(oldFile, newFile);
		} catch (IllegalStateException e) {
			
			e.printStackTrace();
			tbUserEx.setCode(500);
	        tbUserEx.setError("出库添加异常");
	        return tbUserEx;
		} catch (IOException e) {

			e.printStackTrace();
			tbUserEx.setCode(500);
	        tbUserEx.setError("出库添加异常");
	        return tbUserEx;
		}
        
        //字符串分割 WEB-INF 取后面的路径存储到数据
       String arr[] = new_img.split("WEB-INF");
       System.out.println("."+arr[1]);
       //临时文件删除
       oldFile.delete();
        //添加到数据库
       tbOutlibrary.setImg("."+arr[1]);
       tbOutlibrary.setDtime(new Date());
       tbOutlibrary.setLess(0);
       tbOutlibrary.setMany(0);
       tbOutlibrary.setLesswarning(0);
       tbOutlibrary.setManywarning(0);
      
       TbCommodity tbCommodity = null;
       
       try {
    	   //根据id获取库存对象信息
    	   tbCommodity = storageService.getTbCommodityById(tbOutlibrary.getSid());
		} catch (Exception e) {

			e.printStackTrace();
			tbUserEx.setCode(500);
			tbUserEx.setError("添加出库记录异常");
			return tbUserEx;
		}
       
       if(tbCommodity==null) {
    	   tbUserEx.setCode(400);
			tbUserEx.setError("添加出库记录失败");
			return tbUserEx;
       }
       
       tbOutlibrary.setName(tbCommodity.getName());
       //添加到出库
       tbUserEx = outLibrarService.addOutlibrary(tbOutlibrary);
	       
       return tbUserEx;
	}
	
	//出库根据ID删除
	@RequestMapping("/outlibrary-del")
	@ResponseBody
	public TbUserEx outlibraryDel(Integer id,HttpServletRequest request) {
		
		TbUserEx tbUserEx = new TbUserEx();
		Boolean result = false;
		
		try{
			//根据id获取出库对象
			TbOutlibrary tbOutlibrary = outLibrarService.getOutlibraryById(id);
			//对象信息拼凑设定
			String webinf_root = request.getRealPath("/WEB-INF");
			String web_img_path = tbOutlibrary.getImg();
			web_img_path = web_img_path.substring(1, web_img_path.length());
			String old_img = webinf_root.concat(web_img_path);
			File file = new File(old_img);
			file.delete();
			//根据ID删除
			tbUserEx = outLibrarService.delOutlibrary(id);

		}catch(Exception e) {
			e.printStackTrace();
			tbUserEx.setCode(500);
			tbUserEx.setError("出库删除异常");
			return tbUserEx;
		}
		
		return tbUserEx;
	}
	
	//出库编辑操作
	@RequestMapping("/outlibraryedit")
	@ResponseBody
	public TbUserEx outlibraryEdits(TbOutlibrary tbOutlibrary,String dtimes,HttpServletRequest request) {
		
		TbUserEx tbUserEx = new TbUserEx();
		TbOutlibrary old_tbOutlibrary = null;
		try {
			//根据ID获取库存
			TbCommodity tbCommodity = storageService.getTbCommodityById(tbOutlibrary.getSid());
			//设置商品名称
			tbOutlibrary.setName(tbCommodity.getName());
			//时间转换
			SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd");
			tbOutlibrary.setDtime(dateformat.parse(dtimes));
			//根据ID获取出库对象信息
			old_tbOutlibrary = outLibrarService.getOutlibraryById(tbOutlibrary.getId());
		} catch (Exception e1) {

			e1.printStackTrace();
			tbUserEx.setCode(500);
			tbUserEx.setError("出库记录编辑获取异常");
			return tbUserEx;
		}
		
		if(!old_tbOutlibrary.getImg().equals(tbOutlibrary.getImg())) {
			//路径拼接
			String webinf_root = request.getRealPath("/WEB-INF");
			String web_img_path = tbOutlibrary.getImg();
			web_img_path = web_img_path.substring(1, web_img_path.length());
			String old_img = webinf_root.concat(web_img_path);
			String new_img  = old_img.replaceAll("temp", "upload");
			
			
			
			File oldFile=new File(old_img);
			File newFile = new File(new_img);
			
	        //通过CommonsMultipartFile的方法直接写文件（注意这个时候）
	        try {
	        	//文件拷贝临时文件复制到 upload目录
	        	FileUtils.copyFile(oldFile, newFile);
			} catch (IllegalStateException e) {

				e.printStackTrace();
				tbUserEx.setCode(500);
		        tbUserEx.setError("出库编辑异常");
		        return tbUserEx;
			} catch (IOException e) {

				e.printStackTrace();
				tbUserEx.setCode(500);
		        tbUserEx.setError("出库编辑异常");
		        return tbUserEx;
			}
	        
			//字符串分割 WEB-INF 取后面的路径存储到数据
			String arr[] = new_img.split("WEB-INF");
			System.out.println("."+arr[1]);
			  
			//临时文件删除
			oldFile.delete();
				
			String data_old_img = old_tbOutlibrary.getImg();
			String old_web_img_path = data_old_img.substring(1, data_old_img.length());
			String data_old_img_path = webinf_root.concat(old_web_img_path);
			
			File old = new File(data_old_img_path);
			old.delete();
			tbOutlibrary.setImg("."+arr[1]);
			System.out.println("与数据库图片不一样");
		}else {
			System.out.println("与数据库图片一样");
		}
		
		tbUserEx = outLibrarService.editOutlibrary(tbOutlibrary);
		
		return tbUserEx;
	}
	
	//出库编辑页面访问 根据ID获取出库对象信息给页面
	@RequestMapping("/outlibrary-edit")
	public String outlibraryEdit(Integer id,Model model) {
		
		TbOutlibrary tbOutlibrary = null;
		TbUserEx tbUserEx = null;
		
		try{
			tbOutlibrary = outLibrarService.getOutlibraryById(id);
			tbUserEx = storageService.getStorageList();
		}catch(Exception e) {
			e.printStackTrace();
			
		}
		
		model.addAttribute("tbOutlibrary", tbOutlibrary);
		model.addAttribute("tbUserEx", tbUserEx);
		
		return "outlibrary-edit";
	}
	
	//出库页面访问 根据ID获取对象信息系给页面
	@RequestMapping("/outlibrary-out")
	public String outlibraryOut(Integer id,Model model) {
		
		TbCommodity tbCommodity = null;
		
		try {
			tbCommodity = storageService.getTbCommodityById(id);
			
		}catch(Exception e) {
			e.printStackTrace();
		}
		
		model.addAttribute("tbCommodity", tbCommodity);
		
		return "outlibrary-out";
	}
	
	//出库操作
	@RequestMapping("/outlibraryout")
	@ResponseBody
	public TbUserEx outlibraryOuts(TbOutlibrary tbOutlibrary,String dtimes,HttpServletRequest request) {
		
		TbUserEx tbUserEx = new TbUserEx();
		
		TbCommodity tbCommodity = null;
		try {
			
			tbCommodity = storageService.getTbCommodityById(tbOutlibrary.getSid());
			
			if(tbCommodity.getsStorage()>=tbOutlibrary.getOutlibrary()) {
				
				tbCommodity.setsStorage(tbCommodity.getsStorage()-tbOutlibrary.getOutlibrary());
				storageService.editExisStorage(tbCommodity);
			}else {
				tbUserEx.setCode(400);
				tbUserEx.setError("出库数量不能大于库存数量");
				return tbUserEx;
			}
			
			SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd");
			Date date = dateformat.parse(dtimes);
			tbOutlibrary.setDtime(date);
			tbOutlibrary.setSku(String.valueOf(IDUtils.genItemId()));
			tbOutlibrary.setLess(tbCommodity.getLess());
			tbOutlibrary.setLesswarning(tbCommodity.getLesswarning());
			tbOutlibrary.setMany(tbCommodity.getMany());
			tbOutlibrary.setManywarning(tbCommodity.getManywarning());
			
		} catch (Exception e1) {
			
			e1.printStackTrace();
			tbUserEx.setCode(500);
			tbUserEx.setError("出库记录创建获取异常");
			return tbUserEx;
		}
		
		if(!tbCommodity.getImg().equals(tbOutlibrary.getImg())) {
			//路径拼接
			String webinf_root = request.getRealPath("/WEB-INF");
			String web_img_path = tbOutlibrary.getImg();
			web_img_path = web_img_path.substring(1, web_img_path.length());
			String old_img = webinf_root.concat(web_img_path);
			String new_img  = old_img.replaceAll("temp", "upload");
			
			File oldFile=new File(old_img);
			File newFile = new File(new_img);
			
	        //通过CommonsMultipartFile的方法直接写文件（注意这个时候）
	        try {
	        	//文件拷贝临时文件复制到 upload目录
	        	FileUtils.copyFile(oldFile, newFile);
			} catch (IllegalStateException e) {

				e.printStackTrace();
				tbUserEx.setCode(500);
		        tbUserEx.setError("出库创建异常");
		        return tbUserEx;
			} catch (IOException e) {

				e.printStackTrace();
				tbUserEx.setCode(500);
		        tbUserEx.setError("出库创建异常");
		        return tbUserEx;
			}
	        
	        //字符串分割 WEB-INF 取后面的路径存储到数据
	       String arr[] = new_img.split("WEB-INF");
	       System.out.println("."+arr[1]);
	      
	       //临时文件删除
	       oldFile.delete();
			
			tbOutlibrary.setImg("."+arr[1]);
			System.out.println("与数据库图片不一样");
		}else {
			System.out.println("与数据库图片一样");
		}
		
		tbUserEx = outLibrarService.addOutlibrary(tbOutlibrary);
		
		return tbUserEx;
	}
}
